# Author: Liang Bing
# Email: believer19940901@gmail.com
# Phone: 15902720373

# ---------- 加载依赖 ----------
packages <- c("optparse", "ggplot2", "ggsci", "jsonlite", "pacman")
pacman::p_load(char = packages)

# ---------- 工具函数 ----------
`%||%` <- function(a, b) if (!is.null(a)) a else b

# ---------- 参数解析 ----------
parse.opts <- function() {
  option_list <- list(
    make_option(c("-i", "--input_csv"), type = "character", help = "输入 CSV 文件"),
    make_option(c("-c", "--config_json"), type = "character", help = "配置 JSON 文件"),
    make_option(c("-f", "--output_pdf"), type = "character", help = "输出 PDF 路径"),
    make_option(c("-g", "--output_png"), type = "character", help = "输出 PNG 路径")
  )
  parser <- OptionParser(option_list = option_list)
  opts <- parse_args(parser)
  
  # 手动校验
  required <- c("input_csv", "config_json", "output_pdf", "output_png")
  for (field in required) {
    if (is.null(opts[[field]])) {
      print_help(parser)
      stop(paste("缺少必需参数 --", field, sep = ""), call. = FALSE)
    }
  }
  
  return(opts)
}

# ---------- 绘图逻辑 ----------
data.viz <- function(opts) {
  config <- fromJSON(opts$config_json)
  df <- read.csv(opts$input_csv, fileEncoding = "utf-8", stringsAsFactors = FALSE)
  
  p <- ggplot(df, aes(x = X)) +
    geom_histogram(
      color = config$binColor %||% "#808080",
      fill = config$binFill %||% "lightblue",
      bins = config$bins %||% 50
    ) +
    labs(
      x = config$xTitleText %||% "X",
      y = config$yTitleText %||% "Count",
      title = config$pTitleText %||% "Basic Histogram"
    ) +
    switch(
      config$pTheme %||% "bw",
      grey     = theme_grey(),
      bw       = theme_bw(),
      linedraw = theme_linedraw(),
      light    = theme_light(),
      dark     = theme_dark(),
      minimal  = theme_minimal(),
      classic  = theme_classic(),
      void     = theme_void(),
      test     = theme_test(),
      theme_bw()
    ) +
    theme(
      plot.title = element_text(
        family = "Times",
        size   = config$pTitleSize %||% 18,
        color  = config$pTitleColor %||% "#000000",
        face   = "bold"
      ),
      axis.title.x = element_text(
        family = "Times",
        size   = config$xTitleSize %||% 18,
        color  = config$xTitleColor %||% "#000000",
        face   = "bold"
      ),
      axis.title.y = element_text(
        family = "Times",
        size   = config$yTitleSize %||% 18,
        color  = config$yTitleColor %||% "#000000",
        face   = "bold"
      ),
      axis.text.x = element_text(
        size  = config$xTextSize %||% 14,
        color = config$xTextColor %||% "#000000"
      ),
      axis.text.y = element_text(
        size  = config$yTextSize %||% 14,
        color = config$yTextColor %||% "#000000"
      )
    )
  
  # ---------- 保存输出 ----------
  ggsave(opts$output_pdf, plot = p,
         width = config$pWidth %||% 8,
         height = config$pHeight %||% 6)
  ggsave(opts$output_png, plot = p,
         width = config$pWidth %||% 8,
         height = config$pHeight %||% 6,
         dpi = config$pDpi %||% 300)
}

# ---------- 主入口 ----------
main <- function() {
  opts <- parse.opts()
  data.viz(opts)
  quit(status = 0)
}

main()
